package com.greateffect.littlebud.lib.utils;

import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.greateffect.littlebud.lib.adapter.CommonRecyclerAdapter;

/**
 * Created by ZengCS on 2019/3/6.
 * function：recyclerview自动滑动并展示位显示的item
 */
public class AutoScrollUtils {

    /**
     * 滑动左移侧的item显示出来
     * @param recyclerView 需要自动滑动的RecyclerView
     * @param adapter RecyclerView的适配器
     * @param totalCount 数据总数
     * @param curPosition 当前选中的位置 从0开始
     * @param itemRootId 子view的resId,必须为Adapter中顶层view的id 否则将在计算宽度时不正确
     */
    public static void scrollViewToVisible(@NonNull RecyclerView recyclerView, @NonNull CommonRecyclerAdapter adapter, int totalCount, int curPosition, @IdRes int itemRootId){
        if(recyclerView != null  && adapter != null){
            if(totalCount >= 15){
                int parentWidth = recyclerView.getWidth();
                if(parentWidth == 0){
                    parentWidth = recyclerView.getMeasuredWidth();
                }
                View view = adapter.getViewByPosition(recyclerView,curPosition,itemRootId);
                if(view != null){
                    int middle = parentWidth / 2;
                    int childWidth = view.getWidth();
                    if(childWidth <= 0){
                        childWidth = view.getMeasuredWidth();
                    }
                    float sx = view.getX();//view距离父view的x轴位置
                    if(childWidth > 0){
                        sx += childWidth / 2 ;
                        float offValue = sx - middle;
                        //计算距离中间偏移了几个view
                        int offNum = (int) (Math.abs(offValue) / childWidth);
                        if(offNum > 0){//偏离中间时才需要计算
                            if(offValue > 0){//右侧
                                //右侧显示的view个数
                                int rightV = (int) ((middle - offValue) / childWidth);
                                int movePos = curPosition + rightV + offNum;
                                movePos = movePos >= totalCount ? totalCount-1 : movePos;
                                recyclerView.smoothScrollToPosition(movePos);
                            }else if (offValue < 0){//左侧
                                //当前view左侧显示的view个数
                                int leftV = (int) ((middle + offValue) / childWidth);
                                int movePos = curPosition - leftV - offNum;
                                movePos = movePos < 0 ? 0 : movePos;
                                recyclerView.smoothScrollToPosition(movePos);
                            }
                        }
                    }
                }
            }
        }
    }

}
